package com.sta.oldman.tcp;

import com.sta.oldman.coder.TcpMsg;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.util.concurrent.ScheduledFuture;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * WebSocket数据管理器，负责接收外部数据并发送给所有连接的客户端
 */
public class WebSocketDataManager {
    
    // 存储所有连接的客户端Channel
    private final Set<Channel> connectedClients = Collections.synchronizedSet(new HashSet<>());
    
    // 单例模式
    private static final WebSocketDataManager instance = new WebSocketDataManager();
    
    private WebSocketDataManager() {
        // 私有构造函数
    }
    
    public static WebSocketDataManager getInstance() {
        return instance;
    }
    
    /**
     * 添加一个新的客户端连接
     */
    public void addClient(ChannelHandlerContext ctx) {
        connectedClients.add(ctx.channel());
        System.out.println("新客户端连接，当前连接数: " + connectedClients.size());
    }
    
    /**
     * 移除一个客户端连接
     */
    public void removeClient(ChannelHandlerContext ctx) {
        connectedClients.remove(ctx.channel());
        System.out.println("客户端断开连接，当前连接数: " + connectedClients.size());
    }
    
    /**
     * 向所有客户端发送文本消息
     */
    public void sendTextMessageToAll(String message) {
        synchronized (connectedClients) {
            for (Channel channel : connectedClients) {
                if (channel.isActive()) {
                    channel.writeAndFlush(new io.netty.handler.codec.http.websocketx.TextWebSocketFrame(message));
                }
            }
        }
    }
    
    /**
     * 向所有客户端发送TCPMsg格式的数据
     */
    public void sendTcpMsgToAll(TcpMsg tcpMsg) {
        try {
            // 编码为字节数组
            byte[] encodedData = TcpMsgEncoder.encode(tcpMsg);
            
            synchronized (connectedClients) {
                for (Channel channel : connectedClients) {
                    if (channel.isActive()) {
                        channel.writeAndFlush(new BinaryWebSocketFrame(io.netty.buffer.Unpooled.wrappedBuffer(encodedData)));
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 创建并发送一个简单的TCPMsg消息
     */
    public void createAndSendTcpMsg(String content, byte control, byte command) {
        try {
            byte[] data = content.getBytes();
            short length = (short) data.length;
            byte sum = calculateChecksum(data);
            
            TcpMsg tcpMsg = new TcpMsg(control, command, length, data, sum);
            sendTcpMsgToAll(tcpMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // 计算简单校验和的方法
    private static byte calculateChecksum(byte[] data) {
        byte sum = 0;
        for (byte b : data) {
            sum += b;
        }
        return sum;
    }

    public static void main(String[] args) {
        // 在应用的其他部分，通过以下方式发送数据给所有客户端
        WebSocketDataManager manager = WebSocketDataManager.getInstance();

// 发送文本消息
        manager.sendTextMessageToAll("这是一条广播消息！");

// 创建并发送TCPMsg格式的数据
        manager.createAndSendTcpMsg("这是TCPMsg数据", (byte)0x01, (byte)0x02);

// 或者，手动创建TCPMsg对象并发送
        byte[] data = "自定义数据内容".getBytes();
        short length = (short) data.length;
        byte sum = calculateChecksum(data); // 需要实现这个方法
        TcpMsg tcpMsg = new TcpMsg((byte)0x01, (byte)0x03, length, data, sum);
        manager.sendTcpMsgToAll(tcpMsg);
    }
}